/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.estudoJsfJpa.apresentacao.filter;

import br.com.estudoJsfJpa.persistencia.jpa.util.JPAUtil;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

/**
 *
 * @author Paulo Rêgo
 */
@WebFilter(filterName = "ControleTransactionFilter", urlPatterns = {"/*"})
public class ControleTransactionFilter implements Filter {
    
    private FilterConfig filterConfig = null;

    public ControleTransactionFilter() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        try {

            JPAUtil.startTransaction();

            chain.doFilter(request, response);

            JPAUtil.endTransaction(true);

        } catch (Exception ex) {
            ex.printStackTrace();
            JPAUtil.endTransaction(false);
        } finally {
            JPAUtil.clear();
            JPAUtil.close();
        }

    }

    /**
     * Return the filter configuration object for this filter.
     */
    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    /**
     * Destroy method for this filter 
     */
    @Override
    public void destroy() {
    }

    /**
     * Init method for this filter 
     */
    @Override
    public void init(FilterConfig filterConfig) {
        JPAUtil.init("EstudoJPA");
        this.filterConfig = filterConfig;

    }
}
